﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WL.Model;

namespace WL
{
    public partial class FrmFieldAdd : Form
    {
        private int id = -1;

        public FrmFieldAdd()
        {
            InitializeComponent();
        }

        public FrmFieldAdd(int id)
        {
            InitializeComponent();
            this.id = id;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string name = tbName.Text.Replace(" ","");//替换空格
            int pid = Convert.ToInt32(((CmbItem)(cmbTable.SelectedItem)).Id);
            int type = Convert.ToInt32(((CmbItem)(cmbType.SelectedItem)).Id);
            int sort = Convert.ToInt32(tbSort.Text);
            int id = Convert.ToInt32(tbId.Text);

            Field f = new Field();
            f.id = id;
            f.name = name;
            f.typeid = type;
            f.pid = pid;
            f.sortid = sort;
            f.search = rbOpen.Checked == true ? 1 : 0;

            if (Bll.TableService.addOrUpdateField(f)!=null)
            {
                MessageBox.Show("成功");
            }
            
        }
        private void initCmbType()
        {
            cmbType.Items.Add(new CmbItem("0", "数字"));
            cmbType.Items.Add(new CmbItem("1", "文本"));
        }

        private void FrmFieldAdd_Load(object sender, EventArgs e)
        {
            initCmbType();

            DataTable dt = Bll.TableService.getAllTable();

            foreach (DataRow row in dt.Rows)
            {
                CmbItem cb = new CmbItem(row["id"].ToString(), row["name"].ToString());
                cmbTable.Items.Add(cb);
            }

            if (this.id > 0)
            {
                Field f = Bll.TableService.getField(this.id);
                tbName.Text = f.name;
                tbSort.Text = f.sortid+"";
                cmbType.Text = f.type;
                cmbTable.Text = f.table.name;
                tbId.Text = f.id+"";
                //cmbType.ValueMember = f.typeid+"";

            }
        }

        private void cmbTable_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(((CmbItem)cmbTable.SelectedItem).Id);
            Table t = Bll.TableService.getTableById(id);
            //tbIgnore.Text = t.ignore.ToString();
            //dgvErrors.DataSource = t.fields;

            int max = 0;//这个max是用来确定当前表格sortid的，每个表格不能重复，所以求出最大值，插入的时候就插入比最大值+1的
            for (int i = 0; i < t.fields.Count; i++)
            {
                max = max < t.fields[i].sortid ? t.fields[i].sortid : max;
            }
            tbSort.Text = max + 1 + "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
